import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 300000,
  headers: { 'Content-Type': 'application/json' },
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['simuToken'] = `${token}`
    }
    return config
  },
  error => Promise.reject(error),
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const res = response.data

    // 处理特定错误码
    const handleAuthError = code => {
      if ([401, 4001, 999].includes(code)) {
        // localStorage.removeItem('token')
        localStorage.removeItem('userId')
        setTimeout(() => {
          window.location.href = '/'
        }, 1000)
        return true
      }
      return false
    }

    // 检查业务逻辑错误码
    if (res.code && res.code !== 200) {
      if (handleAuthError(res.code)) return Promise.reject(res)
      if (res.code === 400) {
        ElMessage.error(res.msg || 'Mistake')
      }
      return Promise.reject(res)
    }
    return res
  },
  error => {
    const { message } = error
    if (message.includes('timeout')) {
      ElMessage.error('Network timeout')
    } else if (message === 'Network Error') {
      ElMessage.error('Network connection error')
    } else if (error.response && error.response.data) {
      ElMessage.error(error.response.statusText || 'Interface path cannot be found')
    } else {
      ElMessage.error('An unknown error occurred')
    }
    return Promise.reject(error)
  },
)

// 导出 axios 实例
export default service
